package com.mystudy.leetcode.problem.link.p_445;

import com.mystudy.leetcode.base.ListNode;
import com.mystudy.leetcode.base.ListNodeUtils;
import org.junit.Test;

/**
 * @program: infoalgorithm
 * @description: 中等题目:两数相加2
 * @author: zhouzhilong
 * @create: 2019-07-08 13:56
 **/
public class Solution {


    @Test
    public void test() {
        ListNode l1 = ListNodeUtils.generateLinkList(new int[]{5});
        ListNode l2 = ListNodeUtils.generateLinkList(new int[]{5});
        ListNode result = addTwoNumbers(l1, l2);
        ListNodeUtils.show(result);


    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode reverse1 = reverse(l1);
        ListNode reverse2 = reverse(l2);

        ListNode cur1 = reverse1;
        ListNode cur2 = reverse2;

        boolean jw = false;

        ListNode result = null;
        ListNode cur = null;
        while (cur1 != null || cur2 != null || jw ==true) {
            int val1 = cur1 != null ? cur1.val : 0;
            int val2 = cur2 != null ? cur2.val : 0;

            int sum = val1+val2;
            if (jw) {
                sum = sum  + 1;
            }

            if (sum > 9) {
                jw = true;
            } else {
                jw = false;
            }

            ListNode listNode = new ListNode(sum % 10);
            if (result == null) {
                result = listNode;
                cur = result;
            } else {
                cur.next = listNode;
                cur = cur.next;
            }

            cur1 = cur1 != null ? cur1.next : null;
            cur2 = cur2 != null ? cur2.next : null;

        }
        return reverse(result);
    }

    private ListNode reverse(ListNode listNode) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = listNode;

        ListNode prev = dummyHead;
        ListNode cur = listNode;

        while (cur != null && cur.next != null) {
            ListNode nextTemp = cur.next;
            cur.next = nextTemp.next;
            nextTemp.next = prev.next;
            prev.next = nextTemp;
        }
        return prev.next;
    }

}
